package com.vim.modules.web.service;

import com.vim.common.utils.IdGen;
import com.vim.common.base.CrudServiceImpl;
import com.vim.modules.web.model.SysRole;
import com.vim.modules.web.dao.SysRoleMapper;
import com.vim.modules.web.model.SysUserRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysRoleService extends CrudServiceImpl<SysRole> {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Autowired
    public SysRoleService(SysRoleMapper mapper) {
        super(mapper);
    }

    @Override
    public int save(SysRole entity) {
        entity.setRoleId(IdGen.uuid());
        return super.save(entity);
    }

    /**
     * 保存用户角色
     * @param userId
     * @param roleIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRole(String userId, String roleIds) {
        sysRoleMapper.deleteUserRole(userId);
        String[] roleIdList = roleIds.split(",");
        for(String roleId:roleIdList){
            if(StringUtils.isNoneBlank(roleId)){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                sysRoleMapper.saveUserRole(sysUserRole);
            }
        }
    }

    /**
     * 查询用户角色列表
     * @param userId
     */
    public List<SysUserRole> findUserRoleList(String userId) {
        return sysRoleMapper.findUserRoleList(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(String id) {
        sysRoleMapper.delete(id);
        sysRoleMapper.deleteRoleMenu(id);
    }
}

